/* @(#)heart.c
 * Time-stamp: <2008-10-20 00:22:35 root>
 * Copyright 2008 Julian Qian
 * Author: root@localhost.localdomain
 * Version: $Id: heart.c,v 0.0 2008/09/27 13:55:33 root Exp $
 * Keywords: 
 */

#include "common.h"

uint32_t hash_from_key(void *ky){
	KEY *k = (KEY *)ky;
	return (uint32_t)(k->devid);
}

int equal_keys(void *ky1, void *ky2){
	KEY *k1 = (KEY *)ky1;
	KEY *k2 = (KEY *)ky2;
	
	return k1->devid == k2->devid;
}

int travel_hash(){
	int curr_tm, tm, ret;
	KEY *k;
	VALUE *found;
	int ptr = 0;
	devid_t devid;
	PHONE_PAIR upp;

	k = (KEY*) malloc(sizeof(KEY));

	/* printf("## HEART!\n"); */
	
	while(1){
		devid = gDevList[ptr];
		k->devid = devid;
		curr_tm = (int)time(NULL);
		
		if(found = (VALUE*)search_some(gHash, k)){
			
			/* check time, iff > 15min */
			tm = found->up_time;
			if(curr_tm - tm > 15*60){
				/* alarm offline */

				/* query mobile phone to alarm */
				/* db_query_phone(&gDBConn, devid, upp.phone); */
				gDBQ.select_devid = devid;
				mutex_lock(gDBQ.mutex);
				db_stmt_query(gDBQ.select_stmt);
				ret = db_stmt_phone(&gDBQ, upp.phone);
				mutex_unlock(gDBQ.mutex);					
				if( -1 == ret ) {
					continue;
				}
				upp.alarm = 0x4;
				err_msg("##Expired: %s", upp.phone);

				/*
				pthread_t alarm_pid;
				pthread_create(&alarm_pid, NULL, (void *)alarm_user_thread, (PHONE_PAIR *)&upp);
				pthread_join(alarm_pid, NULL);
				*/
				ws_alarm(&upp);
				/* remove expired ones from hash table */
				remove_some(gHash, k);
				gDevList[ptr] = HEART_HOLDER;
			}
		}
		ptr++;
		if(gDevList[ptr] == 0 || ptr >= HEART_MAX) {
			/* ptr = 1; */
			break;
		}
	}
	free(k);
	return 0;
}

int push_heart(devid_t devid){
	int i;
	for (i =0; i< HEART_MAX; i++) {
		if(gDevList[i ] == devid) {
			break;
		}
		if(gDevList[i] == 0 || gDevList[i] == HEART_HOLDER){
			err_msg("##push into heart: %u ", devid);
			
			gDevList[i] = devid;
			break;
		}
	}
	return 0;
}

int Heart(){
	disp_t td = DISPATCH_HEART;
	gDispatcher &= ~td;

	travel_hash();
	return 0;
}


/* heart system */

